package com.liuling;

import com.bean.ClassBean;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.junit.Test;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by huhx on 2017-07-14.
 */
public class HelloVelocity {

    private VelocityEngine init() {
        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        ve.init();
        return ve;
    }

    @Test
    public void velocity_test_1() {
        VelocityEngine ve = init();

        Template t = ve.getTemplate("template/Hellovelocity.vm");
        VelocityContext ctx = new VelocityContext();

        // 数据
        ctx.put("className", "HelloVelocity");
        ctx.put("description", "My first velocity demo.");
        ctx.put("date", (new Date()).toString());

        List temp = new ArrayList();
        temp.add("username");
        temp.add("password");
        ctx.put("list", temp);

        StringWriter sw = new StringWriter();
        t.merge(ctx, sw);
        System.out.println(sw.toString());
    }

    @Test
    public void velocity_test_2() {
        VelocityEngine ve = init();

        Template t = ve.getTemplate("template/ClassVelocity.vm");
        VelocityContext ctx = new VelocityContext();

        // 数据
        List<ClassBean> classBeans = new ArrayList<>();
        ClassBean classBean1 = new ClassBean();
        classBean1.setName("username");
        classBean1.setComment("用户名");

        ClassBean classBean2 = new ClassBean();
        classBean2.setName("password");
        classBean2.setComment("密码");

        ClassBean classBean3 = new ClassBean();
        classBean3.setName("address");
        classBean3.setComment("地址");

        classBeans.add(classBean1);
        classBeans.add(classBean2);
        classBeans.add(classBean3);

        ctx.put("className", "Person");
        ctx.put("list", classBeans);

        StringWriter sw = new StringWriter();
        t.merge(ctx, sw);
        System.out.println(sw.toString());
    }
}
